package edu.tongji.engine.service;

import edu.tongji.engine.db.dao.DAOFactory;
import edu.tongji.engine.db.dao.IProcessDao;
import edu.tongji.engine.db.dao.ITokenDao;
import edu.tongji.engine.def.ProcessDefinition;
import edu.tongji.engine.def.parser.ProcessParser;
import edu.tongji.engine.exe.ProcessInstance;
import edu.tongji.engine.exe.Token;

public class ProcessService {

	private IProcessDao processDao;
	private TokenService tokenService = new TokenService();
	private ProcessDefinition pd =null;
	private ProcessInstance pi = null;
	
	public ProcessService(){
		processDao = DAOFactory.createProcessDao();
		pd = new ProcessDefinition();
		//pi = new ProcessInstance();
	}
	public ProcessService(String processInstanceName){
		processDao = DAOFactory.createProcessDao();
		pd = new ProcessDefinition();
		pi = processDao.getProcessInstance(processInstanceName);
	}
	
	public ProcessDefinition getProcessDefinition( String processName ){
	
			ProcessDefinition pd = processDao.getProcessDefinition(processName);
			return pd;
	}
	
	public boolean createProcessDefinition(ProcessDefinition pd){
		return processDao.saveProcessDefition(pd);
	}
	
	public boolean deployProcessDefinition(String fileName){
		ProcessParser parser = new ProcessParser();
		ProcessDefinition pd = parser.parser(fileName);
		return this.createProcessDefinition(pd);
		
	}
	
	public boolean createProcessInstance(String processDefinitionName, 
			String processInstanceName ){
		//create ProcessInstance including create token and context
		if( processDefinitionName.equals(null) ){
			return false;
		}else{
			
			pd = processDao.getProcessDefinition(processDefinitionName);
			ProcessInstance pi = new ProcessInstance();
			pi.setName(processInstanceName);
			pi.setPd(pd);
			Token token = new Token();
			pi.setToken(token);
			token.setNode(pd.getStartNode());
			
			return processDao.saveProcessInstance(pi);
		}
	}
	
	public ProcessInstance getProcessInstance(String processInstanceName){
		return processDao.getProcessInstance(processInstanceName);
	}
	
	public void next(String processInstanceName){
		ProcessInstance pi = processDao.getProcessInstance(processInstanceName);
		if ( pi == null ){
			System.out.println("initial processInstance failed, please use constractor with String parameter");
		}else{
			tokenService.next(pi.getToken());
		}
	}
//	public ProcessDefinition getProcessDefinition( Long processId ){
//		return processDao.getProcess(processId);
//	}
}
